import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './chat-history.module.css';
import { useSearchParams } from 'react-router-dom';
export default function ChatHistory() {
  const [sessions, setSessions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [tipMsg, setTipMsg] = useState(null);
  const [isSuccessTip, setIsSuccessTip] = useState(false);
  const navigate = useNavigate();
  const [SearchParams] = useSearchParams();
  const email = SearchParams.get('email'); // 获取当前用户email

  useEffect(() => {
    const fetchSessions = async () => {
      try {
        const response = await fetch('http://localhost:5000/api/session/all');
        if (!response.ok) throw new Error(`请求失败: ${response.statusText}`);
        
        const data = await response.json();
        const userSessions = email 
          ? data.filter(session => session.email === email) 
          : data;
        // 2. 再按最后更新时间排序
        const sortedSessions = userSessions.sort((a, b) => 
          new Date(b.lastUpdate).getTime() - new Date(a.lastUpdate).getTime()
        );
        
        setSessions(sortedSessions);
      } catch (err) {
        showTip(err instanceof Error ? err.message : '获取会话失败，请重试', false);
      } finally {
        setLoading(false);
      }
    };
    fetchSessions();
  }, [email]); // 依赖项添加email，当email变化时重新获取筛选

  // 其余代码保持不变...
  const showTip = (msg, isSuccess) => {
    setTipMsg(msg);
    setIsSuccessTip(isSuccess);
    setTimeout(() => {
      setTipMsg(null);
      setIsSuccessTip(false);
    }, 3000);
  };

  const handleSessionClick = (sessionId) => {
    navigate(`/HeroSection/session?sessionId=${sessionId}&email=${email}`);
    console.log(sessionId);
  };

  const formatSessionTime = (timeString) => {
    const date = new Date(timeString);
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const sessionDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    const diffDays = Math.ceil((today.getTime() - sessionDate.getTime()) / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    if (diffDays === 1) return '昨天';
    if (diffDays < 7) return ['周日','周一','周二','周三','周四','周五','周六'][date.getDay()];
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
  };

  const getLastMessagePreview = (messages) => {
    if (messages.length === 0) return '未开始对话';
    
    const lastMessage = messages.sort((a, b) => 
      new Date(b.date).getTime() - new Date(a.date).getTime()
    )[0];
    
    return lastMessage.role === 'user' 
      ? `我: ${lastMessage.content.slice(0, 25)}${lastMessage.content.length > 25 ? '...' : ''}` 
      : `AI: ${lastMessage.content.slice(0, 25)}${lastMessage.content.length > 25 ? '...' : ''}`;
  };

  const handleDeleteSession = async (sessionId, e) => {
    e.stopPropagation();
    
    try {
      const response = await fetch(`http://localhost:5000/api/session/delete?sessionId=${sessionId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
      });

      if (!response.ok) throw new Error(`删除失败: ${response.statusText}`);
      
      setSessions(prev => prev.filter(session => session.id !== sessionId));
      showTip('会话删除成功', true);
    } catch (err) {
      showTip(err instanceof Error ? err.message : '删除失败，请重试', false);
    }
  };

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <div className={styles.spinner}></div>
        <p className={styles.loadingText}>加载历史会话中...</p>
      </div>
    );
  }

  if (sessions.length === 0) {
    return (
      <div className={styles.emptyContainer}>
        <span className={styles.emptyIcon}>📭</span>
        <p className={styles.emptyText}>暂无历史会话</p>
        <p className={styles.emptyTip}>点击"新增会话"开始新对话吧</p>
      </div>
    );
  }

  return (
    <div className={styles.chatHistoryContainer}>
      <div className={styles.historyHeader}>
        <h3 className={styles.headerTitle}>历史会话</h3>
        <span className={styles.sessionCount}>{sessions.length} 个会话</span>
      </div>

      {tipMsg && (
        <div className={`${styles.tipBar} ${isSuccessTip ? styles.successTip : styles.errorTip}`}>
          <span className={styles.tipIcon}>{isSuccessTip ? '✅' : '⚠️'}</span>
          <span className={styles.tipText}>{tipMsg}</span>
        </div>
      )}

      <div className={styles.sessionList}>
        {sessions.map((session) => (
          <div 
            key={session.id}
            className={styles.sessionItem}
            title={`${session.mask.name} - ${session.topic}`}
            onClick={() => handleSessionClick(session.id)}
          >
            <div className={styles.maskAvatar}>
              {session.mask.avatar && !['asd', 'asdf', 'asdfg', 'asdfgh'].includes(session.mask.avatar) 
                ? (
                  <img 
                    src={session.mask.avatar} 
                    alt={session.mask.name}
                    className={styles.avatarImage}
                  />
                ) : (
                  <span className={styles.avatarText}>{session.mask.name.charAt(0)}</span>
                )
              }
            </div>

            <div className={styles.sessionInfo}>
              <div className={styles.sessionHeader}>
                <h4 className={styles.sessionTopic}>{session.topic}</h4>
                <span className={styles.sessionTime}>{formatSessionTime(session.lastUpdate)}</span>
              </div>
              <p className={styles.lastMessage}>{getLastMessagePreview(session.messages)}</p>
              <span className={styles.maskTag}>{session.mask.name}</span>
            </div>

            <button
              className={styles.deleteBtn}
              onClick={(e) => handleDeleteSession(session.id, e)}
              title="删除会话"
            >
              删除
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}